package logic

import (
	"context"
	"fmt"
	"usershop/api/pkg"
	"usershop/user_srv/user"

	"usershop/api/internal/svc"
	"usershop/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RegisterLogic) Register(req *types.RegisterShop) (resp *types.ResMsg, err error) {
	// todo: 用户注册 绑定手机号

	//手机格式效验
	format := pkg.TelFormat(req.Tel)

	if format == false {
		return &types.ResMsg{
			Cre:  -2,
			Msg:  "手机号格式错误",
			Data: nil,
		}, err
	}

	salt := pkg.GenerateRandomstring(5) //盐
	fmt.Println("盐......", salt)
	md5 := pkg.Md5String(req.Password + salt) //加密
	fmt.Println("加盐加密后的...................", md5)
	_, err = l.svcCtx.UserSrv.RegisterUser(l.ctx, &user.ResisterUserRequest{
		Username: req.Username,
		Password: md5,
		Sale:     salt,
		Tel:      req.Tel,
	})

	if err != nil {
		return &types.ResMsg{
			Cre:  0,
			Msg:  "注册失败",
			Data: nil,
		}, nil
	}

	return &types.ResMsg{
		Cre:  0,
		Msg:  "注册成功",
		Data: nil,
	}, nil
}
